<?php

namespace Dls\Entity\V0\Form\Field;

use Dls\Entity\V0\Form\Field;

class Select extends Field
{
    const
        TYPE_SELECT = 'select',
        TYPE_BUTTONG = 'button';

    private $each = [];
    private $groupBy = '';
    protected $config = [];
    private $enum;
    protected $type = 'select';
    protected $multi = false;

    /**
     * 设置多选
     *
     * @return $this
     */
    public function multi()
    {
        $this->multi = true;
        return $this;
    }

    /**
     *  data-key:xxx;data-value:xxx
     *
     * @param string $key
     * @param string $value
     * @return $this
     */
    public function each(string $key, string $value)
    {
        $this->each = [$key, $value];
        return $this;
    }

    /**
     * 设置data-groupBy字段的值，支持下拉框的分组
     *
     * @param string $groupBy
     * @return $this
     */
    public function groupBy(string $groupBy)
    {
        $this->groupBy = $groupBy;
        return $this;
    }

    /**
     * 设置data-enum的值
     * support:
     *     eg1: 1,xxx;2,xxx
     *     eg2: http://xxxxx
     *
     * @param string $enum
     * @return $this
     */
    public function enum(string $enum)
    {
        $this->enum = $enum;
        return $this;
    }

    /**
     * 设置 select 类型 [select, button]
     *
     * @param string $type
     */
    public function type(string $type = self::TYPE_SELECT)
    {
        $this->type = $type;
        return $this;
    }


    /**
     * Set config for select2.
     *
     * @param string $key
     * @param mixed  $val
     *
     * @return $this
     */
    public function config($key, $val)
    {
        $this->config[$key] = $val;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function render()
    {
        $var = [
            'enum' => $this->enum,
            'groupBy' => $this->groupBy,
            'dataKey' => $this->each[0] ?? '',
            'dataValue' => $this->each[1] ?? '',
            'multi' => $this->multi,
        ];

        $this->addVariables($var);

        isset($this->attributes['data-fn']) || $this->attribute('data-fn', $this->type == self::TYPE_SELECT ? 'form-select' : 'form-button');

        return parent::render();
    }
}
